import jwt
from flask import Blueprint, jsonify, current_app ,send_file
from flask_restful import Api, Resource,reqparse
from utils.smscode import sms_code
from utils.myredis import r
from models.user.user import User,db
from captcha.image import ImageCaptcha


login_bp = Blueprint('login_bp', __name__, url_prefix='/')
api = Api(login_bp)

import random
import time
import redis

# 图片验证码
class ImgView(Resource):
    def get(self,uuid):
        img = ImageCaptcha()
        code = random.randint(1000,9999)
        code1 = str(code)
        img_png = img.generate(code1)
        r.str_setex('code_%s'%uuid,code1,3600)
        return send_file(img_png,mimetype="png")

api.add_resource(ImgView,'/img/<uuid>')

# 发送手机验证码
class SmsView(Resource):
    def get(self, mobile):
        req = reqparse.RequestParser()
        uuid = req.add_argument('uuid')
        req.add_argument('imgcode')
        args = req.parse_args()

        imgcode = r.str_get(uuid)
        if imgcode != args['imgcode']:
            return jsonify({'code':400,'msg':'图片验证码错误'})

        smscode = str(random.randint(1000, 9999))
        sms_code(mobile,smscode)
        r.str_setex(mobile,60,smscode)
        time.sleep(2)
        return jsonify({'code':200,'msg':'ok'})
api.add_resource(SmsView, '/sms/<mobile>')



class LoginView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('nikename')
        req.add_argument('mobile')
        args = req.parse_args()

        if not all([args['nikename'],args['mobile']]):
            return jsonify({
                'code':400,
                'msg':'数据不完整'
            })

        user = User.query.filter(User.username == args['nikename']).first()
        if not user:
            u = User(nikename=args['nikename'], mobile=args['mobile'])
            db.session.add(u)
            db.session.commit()
            return jsonify({'code': 200, 'msg': '注册成功'})

        if user.mobile != args['mobile']:
            return jsonify({
                'code':400,
                'msg':'信息错误'
            })

        key = current_app.config.get('SECRET_KEY')
        token = jwt.encode({
            'user_id': user.id,
            'exp': int(time.time()) + 30
        }, key, algorithm='HS256')
        return jsonify({'code': 200, 'msg': '登录成功', 'token': token})



api.add_resource(LoginView,'/login')







